package thread.gc;

import lombok.extern.log4j.Log4j2;


import java.math.MathContext;
import java.util.Random;
import java.util.UUID;

/**
 * @author ykh
 */
@Log4j2
public class ExerciseTransfer {
    public static void main(String[] args) throws InterruptedException {
        Account a = new Account(UUID.randomUUID().toString(),1000);
        Account b = new Account(UUID.randomUUID().toString(),1000);
        Thread t1 = new Thread(() -> {
            for (int i = 0; i < 1000; i++) {
                a.transfer(b, randomAmount());
            }
        }, "t1");
        Thread t2 = new Thread(() -> {
            for (int i = 0; i < 1000; i++) {
                b.transfer(a, randomAmount());
            }
        }, "t2");
        t1.start();
        t2.start();
        t1.join();
        t2.join();
        // 查看转账2000次后的总金额
        log.debug("total:{}", (a.getMoney() + b.getMoney()));
    }

    // Random 为线程安全
    static Random random = new Random();

    // 随机 1~100
    public static int randomAmount() {
        return random.nextInt(100) + 1;
    }
}

class Account {
    private String UUID;
    private int money;

    public Account(String UUID,int money) {
        this.UUID = UUID;
        this.money = money;
    }

    public int getMoney() {
        return money;
    }

    public void setMoney(int money) {
        this.money = money;
    }

    public String getUUID() {
        return UUID;
    }


    //向target转账
    public void  transfer(Account target, int amount) {
//            synchronized (
//                    target.getUUID().compareTo(this.getUUID()) <= 0 ?
//                    (target.getUUID()+this.getUUID()).intern() :
//                    (this.getUUID()+target.getUUID()).intern()
//            ){
                if (this.money > amount) {
                    this.setMoney(this.getMoney() - amount);
                    target.setMoney(target.getMoney() + amount);
                }
//            }
    }
}
